package app.conn;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class HttpConnector {

	private HttpURLConnection conn;
	
	private URL urlObj;

	private boolean dataSent;

	private int responseCode;

	/**
	 * Constructor. Prepare connection to the server
	 * 
	 * @param url Server URL
	 * @throws IOException Connection error
	 */
	public HttpConnector(String url) throws IOException { 
		dataSent = false;

		// create URL
		urlObj = new URL(url);
	}

	/**
	 * Sending method using POST request method.
	 * 
	 * @param parameters String array with parameters in form: key=value
	 * @return True, if response is OK
	 * @throws IOException Sending data error
	 */
	public boolean send(String[] parameters) throws IOException {
		System.out.println("SEND DATA");
		for(String s : parameters) {
			System.out.println(s);
		}

		// create connection
		conn = (HttpURLConnection) urlObj.openConnection();
		// set http header
		conn.setRequestMethod("POST");
		conn.setRequestProperty("User-Agent", "client");
		conn.setDoOutput(true);

		// concat url parameters
		StringBuffer param = new StringBuffer();
		param.append(parameters[0]);
		for (int i = 1; i < parameters.length; i++) {
			param.append("&");
			param.append(parameters[i]);
		}

		// send request
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.writeBytes(param.toString());
		out.flush();
		out.close();

		responseCode = conn.getResponseCode(); 
		if(responseCode == 200) {
			dataSent = true;
			return true;
		}
		return false;
	}

	/**
	 * Receive all data from the server
	 * 
	 * @return String with all response
	 * @throws IOException Data receiving error
	 */
	public String[] receive() throws IOException {
		if(!dataSent) {
			return null;
		}
		else {
			dataSent = false;

			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			List<String> buffer = new ArrayList<String>();
			while((line = in.readLine()) != null) {
				buffer.add(line);
			}
			in.close();
			conn.disconnect();
			System.out.println("RECEIVE DATA");
			for(String s : buffer) {
				System.out.println("> ".concat(s));
			}

			return buffer.toArray(new String[0]);
		}
	}

	/**
	 * Get last response code
	 * 
	 * @return Last response code
	 */
	public int getResponseCode() {
		return responseCode;
	}

	/**
	 * MD5 Encrypt function, same to PHP md5()
	 * 
	 * @param input String to encrtypt
	 * @return Encrypted string
	 * @throws NoSuchAlgorithmException Algorithm not found
	 */
	public static String md5(String input) throws NoSuchAlgorithmException {
		String result = input;
		if(input != null) {
			MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
			md.update(input.getBytes());
			BigInteger hash = new BigInteger(1, md.digest());
			result = hash.toString(16);
			while(result.length() < 32) { //40 for SHA-1
				result = "0" + result;
			}
		}
		return result;
	}
}

